package com.gem.demo.mvc;

import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class WebInterceptor implements HandlerInterceptor {
    /**
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     *
     * 登录验证：
     * 拦截所有请求
     * 对于登录请求放行
     * 非登录请求进行登录验证（currUser是否为空）
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri=request.getRequestURI();
        System.out.println(uri);
        if (uri.endsWith("/login")||uri.endsWith("/toLogin")||uri.endsWith("/")){
            //登录请求 放行
            return true;
        }
        HttpSession session =request.getSession();
        Object user=session.getAttribute("curruser");
           if (user==null){
               //未登录
               //跳转到登录页
               response.sendRedirect(request.getContextPath()+"toLogin");
               return false;
           }
        return true;
    }
}
